package com.tjoris.midigateway.ui;

import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.AbstractCellEditor;
import javax.swing.JSlider;
import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.TableCellEditor;

import com.tjoris.midigateway.IMidiActionListener;

public class TestEditor extends AbstractCellEditor implements TableCellEditor
{
    private static final long serialVersionUID = 7999906529333024345L;
    
	private final IMidiActionListener fListener;
	private final TestCell fCell;
	private MidiEntry fMidiEntry = null;

	public TestEditor(final IMidiActionListener listener)
	{
		fListener = listener;
		fCell = new TestCell();
		fCell.getButton().addMouseListener(new MouseAdapter()
		{
            public void mousePressed(final MouseEvent e)
            {
				fListener.triggerAction(fMidiEntry.getAction(), true, 0);
            }

            public void mouseReleased(MouseEvent e)
            {
				fListener.triggerAction(fMidiEntry.getAction(), false, 0);
            }
		});
		fCell.getSlider().addChangeListener(new ChangeListener()
		{
			public void stateChanged(final ChangeEvent e)
			{
				final JSlider source = (JSlider)e.getSource();
	            final int value = source.getValue();
	            fMidiEntry.setLastValue(value);
	            fListener.triggerAction(fMidiEntry.getAction(), true, value);
			}
		});
	}
	
	public Object getCellEditorValue()
	{
	    return fMidiEntry;
	}

	public Component getTableCellEditorComponent(final JTable table, final Object value, final boolean isSelected, final int row, final int column)
	{
		fMidiEntry = (MidiEntry)value;
		return fCell.getComponent(fMidiEntry, table, isSelected);
	}
}